package com.material.vtool.service.impl;

import com.material.vtool.entity.BUserDownloadInfoEntity;
import com.material.vtool.entity.respEntity.ReturnCode;
import com.material.vtool.exception.ServiceException;
import com.material.vtool.mapper.MaterialInfoMapper;
import com.material.vtool.mapper.UserDownloadInfoMapper;
import com.material.vtool.mapper.UserInfoMapper;
import com.material.vtool.service.UserDownloadInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.locks.ReentrantLock;

@Service
public class UserDownloadInfoServiceImpl implements UserDownloadInfoService {
    private final ReentrantLock materialDownloadLock = new ReentrantLock();

    private final ReentrantLock userDownloadLock = new ReentrantLock();

    @Autowired
    private UserDownloadInfoMapper userDownloadInfoMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private MaterialInfoMapper materialInfoMapper;

    /**
     * 保存用户下载
     * @param userId 下载用户ID
     * @param materialId 文章ID
     * @return
     */
    @Override
    @Transactional
    @Async
    public Integer saveUserDownloadLog(Integer userId, Integer materialId) {
        // 保存用户下载
        Integer affectedCount = userDownloadInfoMapper.insertObject(userId, materialId);
        if (affectedCount == null || affectedCount.intValue() == 0) throw new ServiceException("保存失败", ReturnCode.SERVER_ERROR);

        // 用户下载次数 + 1
        try {
            userDownloadLock.lock();
            Integer affectedCount1 = userInfoMapper.increaseDownloadCount(userId);
            if (affectedCount1 == null || affectedCount1.intValue() == 0) throw new ServiceException("更新用户下载次数失败", ReturnCode.SERVER_ERROR);
        }  finally {
            userDownloadLock.unlock();
        }

        // 文章下载次数 + 1
        try {
            materialDownloadLock.lock();
            Integer affectedCount2 = materialInfoMapper.increaseDownloadCount(materialId);
            if (affectedCount2 == null || affectedCount2.intValue() == 0) throw new ServiceException("更新文章下载次数失败", ReturnCode.SERVER_ERROR);
        } finally {
            materialDownloadLock.unlock();
        }

        return affectedCount;
    }

    @Override
    public BUserDownloadInfoEntity getUserDownloadInfo(Integer userId, Integer materialId) {
        return userDownloadInfoMapper.getUserDownloadInfo(userId, materialId);
    }

    @Override
    public int updateUserDownLoad(BUserDownloadInfoEntity bUserDownloadInfoEntity) {
        Integer affectedCount = userDownloadInfoMapper.updateUserDownLoad(bUserDownloadInfoEntity);
        if (affectedCount == null || affectedCount.intValue() == 0) throw new ServiceException("更新失败", ReturnCode.SERVER_ERROR);
        return affectedCount.intValue();
    }
}
